<template>
  <continer :isNoTabs="true">
    <template slot="search">
      <div
        style="overflow: hidden"
        :style="{
          height: openShow ? 'auto' : '80px',
        }"
      >
        <el-form
          id="searchForm"
          :model="formData"
          label-position="top"
          style="display: flex; flex-wrap: wrap; height: auto"
          @submit.native.prevent
        >
          <el-form-item
            style="margin-right: 20px"
            :label="item.name"
            v-for="(item, index) in chooseFilterField"
            :key="index"
            :prop="item.field"
          >
            <input-type
              :filterModule="true"
              :propData="item"
              :searchShow="true"
              :propValue="formData[item.field]"
              @updatePropValue="updatePropValue"
              @querySearch="handleSearchFunc"
            ></input-type>
            <template v-if="item.type === 'number-range'">
              <template slot="label">
                <span>{{ item.name }}</span>
                <el-tooltip content="区间最小值和最大值必填" placement="top">
                  <i
                    style="
                      font-size: 12px;
                      color: #b3b9c7;
                      margin-left: 6px;
                      cursor: pointer;
                    "
                    class="V7_iconfont V7_iconV7tubiao_bangzhu-42"
                  ></i>
                </el-tooltip>
              </template>
              <el-input-number
                v-model="formData[item.field][0]"
                :controls="false"
                size="small"
                :precision="0"
                :min="0"
                :max="formData[item.field][1]"
                @blur="handleSearchFunc"
              />
              <span style="margin: 0 6px">-</span>
              <el-input-number
                v-model="formData[item.field][1]"
                :controls="false"
                size="small"
                :precision="0"
                :min="formData[item.field][0] ? formData[item.field][0] : 0"
                @blur="handleSearchFunc"
              />
            </template>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template slot="oprate">
      <div v-if="searchHeight > 100" @click="handleLines" class="open">
        <i :class="openShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />{{
          openShow ? "收起" : "展开"
        }}
      </div>
      <customFilter
        name="自定义"
        :chooseData="chooseFilterField"
        :getCusAllFields="searchFields"
        @saveFilter="saveFilter"
      />
      <!-- <customSearch
        ref="customSearch"
        class="customSearch"
        :fieldList="fieldList"
        :fieldSelectList="fieldSelectList"
        :customList="customList"
        :conditionList="conditionList"
        @deleteCustomClick="deleteCustomClick"
        @popverShow="popverShow"
        @saveCondition="saveConditionFun"
        @handleSearch="handleSearch"
      ></customSearch> -->
      <el-button type="primary" size="mini" @click="handleSearchFunc"
        >查询</el-button
      >
    </template>
    <template slot="content">
      <configTable
        v-if="isShowTabel"
        v-loading="showLoading"
        ref="table"
        :headers="tableHeaders"
        :data="qualityTableData"
        :pagingData="pagingData"
        :headersConfig="true"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="item.show && !['oprate'].includes(item.prop)"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :resizable="true"
              :min-width="item.width"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
            >
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'oprate'"
              :key="index"
              :label="item.label"
              :resizable="false"
              :width="100"
              fixed="right"
            >
              <template slot-scope="scope">
                <span
                  class="oprate-span"
                  @click="toDetail(scope.row)"
                  v-functions="['qc_webchat_session_query_detail']"
                  >详情</span
                >
                <span
                  v-functions="['qc_webchat_session_query_log']"
                  class="oprate-span"
                  @click="toLog(scope.row)"
                  >日志</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <commonDrawer
        :title="drawerName"
        :drawer="drawerShow"
        :size="logShow ? 520 : 700"
        :isShowMoreBtn="false"
        @closeDraw="closeDraw"
      >
        <template slot="column">
          <Log
            v-if="logShow"
            ref="qualityLog"
            :logData="qualityLogs"
            :chatSessionId="resultId"
          />
          <ResultDetail
            v-else
            ref="resultDetail"
            :sessionId="currentSessionId"
            :visitorId="currentVisitorId"
            :scoringId="resultId"
            :resultsData="qualityResults"
            :modelsList="modelsList"
          />
        </template>
      </commonDrawer>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref, Prop } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import { commonAction, deepClone, millsToDate } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import inputType from '@/views/newCustomer/common/inputType.vue'
import customFilter from '@/components/customFilter/index.vue'
import commonDrawer from '@/components/globalTool/resizeDrawer/drawer.vue'
import Log from '@/views/qualityCheck/result/log.vue'
import ResultDetail from '@/views/qualityCheck/result/resultDetail.vue'
import customSearch from '@/views/dataCenter/callData/customSearch.vue'
import { WebchatModule } from '@/store/modules/webchat'
@Component({
  name: 'resultQuery',
  components: {
    configTable,
    continer,
    inputType,
    customFilter,
    commonDrawer,
    Log,
    ResultDetail,
    customSearch
  }
})
export default class ResultQuery extends Vue {
  [x: string]: any
  @Ref() private qualityLog
  @Ref() private resultDetail

  private openShow: boolean = false

  private chooseFilterField: any = []

  private customFilterUpdateId: any = '' // 更新自定义搜索的id

  private customHeaderUpdateId: any = '' // 更新自定义表头的id

  private searchHeight: any = 0

  private formData: any = {
    agentFirstReplyLength: [],
    totalMessageCount: [],
    agentReplyMessageCount: [],
    sesssionTimeLength: [],
    gradeScore: []
  }

  private checkHeaders: any = []

  private qualityTableData: any = []

  private qualityLogs: any = [] // 日志

  private qualityResults: any = [] // 详情

  private drawerName: any = ''

  private drawerShow: boolean = false

  private pagingData = { total: 0, limit: 10, page: 1 }

  private logShow: boolean = false

  private resultId: any = ''

  private modelsList: any = []

  private showLoading: boolean = false

  private isShowTabel: boolean = false

  // 评分详情字段
  private currentSessionId: string = ''
  private currentVisitorId: string = ''

  private tableHeaders: object[] = [
    { label: '客户名称', prop: 'visitorName', show: true },
    { label: '会话记录ID', prop: '_id', show: true, width: 120 },
    { label: '技能组', prop: 'queueName', show: true },
    { label: '座席名称', prop: 'agentName', show: true },
    { label: '会话结束类型', prop: 'finishReason', show: true, width: 120 },
    { label: '创建时间', prop: 'createTime', show: true },
    { label: '渠道接入号', prop: 'accessName', show: true, width: 120 },
    { label: '首响时长', prop: 'agentFirstReplyLength', show: true },
    { label: '总消息数', prop: 'totalMessageCount', show: true },
    { label: '座席消息数', prop: 'agentReplyMessageCount', show: true, width: 100 },
    { label: '满意度名称', prop: 'satisfactionName', show: true, width: 120 },
    { label: '对话时长', prop: 'sesssionTimeLength', show: true },
    { label: '座席提交时间', prop: 'applyQualityTime', show: true, width: 120 },
    { label: '质检模板', prop: 'name', show: true },
    { label: '质检分数', prop: 'gradeScore', show: true },
    { label: '分数段评级', prop: 'scoreRange', show: true, width: 120 },
    { label: '质检时间', prop: 'qualityTime', show: true },
    { label: '质检人', prop: 'qualityUserName', show: true },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  private finishKeyOpt: any = [] // 会话结束类型

  get queueList () {
    return (CommonModule as any).publicCache.queueList.map(v => ({
      value: v.name,
      key: v._id
    }))
  }

  get getUserList () {
    return (CommonModule as any).publicCache.userList.map(v => ({ value: `${v.agentName} 【${v.agentNumber}】`, key: v._id }))
  }

  get accessIdOpt () {
    return (CommonModule as any).publicCache.channelList.map(v => ({
      value: v.name,
      key: v.accessId
    }))
  }

  private searchFields: any = [ // 自定义搜索
    { name: '客户名称', field: 'visitorName', type: 'text' },
    { name: '会话记录ID', field: '_id', type: 'text' },
    { name: '技能组', field: 'toPeer', type: 'dropdown' },
    { name: '座席名称', field: 'userId', type: 'dropdown' },
    { name: '会话结束类型', field: 'finishReason', type: 'dropdown' },
    { name: '创建时间', field: 'createTime', type: 'datetime-range' },
    { name: '渠道接入号', field: 'accessId', type: 'dropdown' },
    { name: '首响时长(s)', field: 'agentFirstReplyLength', type: 'number-range' },
    { name: '总消息数', field: 'totalMessageCount', type: 'number-range' },
    { name: '座席消息数', field: 'agentReplyMessageCount', type: 'number-range' },
    { name: '满意度名称', field: 'satisfactionData.satisfactionName', type: 'text' },
    { name: '对话时长(s)', field: 'sesssionTimeLength', type: 'number-range' },
    { name: '座席提交时间', field: 'applyQualityTime', type: 'datetime-range' },
    { name: '质检模板', field: 'name', type: 'dropdown' },
    { name: '质检分数', field: 'gradeScore', type: 'number-range' },
    { name: '分数段评级', field: 'scoreRange', type: 'text' },
    { name: '质检时间', field: 'qualityTime', type: 'datetime-range' },
    { name: '质检人', field: 'qualityUser', type: 'dropdown' }
  ]

  // 高级筛选参数
  private customList: any = []

  private fieldList = [ // 自定义筛选项
    { label: '客户昵称', prop: 'visitorName' },
    { label: '会话ID', prop: '_id' },
    { label: '渠道来源', prop: 'platform' },
    { label: '渠道接入号', prop: 'accessId' },
    { label: '技能组', prop: 'toPeer' },
    { label: '座席名称/工号', prop: 'userId' },
    // { label: '座席昵称', prop: 'userId' },
    { label: '会话状态', prop: 'status' },
    { label: '创建时间', prop: 'createTime' },
    { label: '转人工时间', prop: 'convertManualTime' },
    { label: '转人工成功时间', prop: 'manualTime' },
    { label: '结束时间', prop: 'endTime' },
    { label: '首响时间', prop: 'agentFirstReplyTime' },
    { label: '总消息条数', prop: 'totalMessageCount' },
    { label: '访客消息条数', prop: 'visitorMessageCount' },
    { label: '座席消息条数', prop: 'agentReplyMessageCount' },
    { label: '访问来源', prop: 'seoSource' },
    { label: '访问来源关键字', prop: 'seoKeywords' },
    { label: '会话结束类型', prop: 'finishKey' },
    { label: '地域', prop: 'area' },
    { label: 'IP地址', prop: 'ip' },
    { label: '会话类型', prop: 'sessionType' },
    { label: '满意度名称', prop: 'satisfactionData.satisfactionName' },
    { label: '会话标签', prop: 'sessionTags' },
    { label: '会话内容', prop: 'messageKeywords' },
    { label: '质检模板', prop: 'qualityConfigName' },
    { label: '质检分数', prop: 'gradeScore' },
    { label: '分数段评级', prop: 'scoreRange' },
    { label: '质检时间', prop: 'qualityTime' },
    { label: '质检人', prop: 'qualityUser' }
  ]

  private fieldSelectList = {
    accessId: [],
    qualityUser: this.getUserList
  }

  private conditionList = { // 自定义筛选项条件
    // 'eq'（等于）, 'neq'（不等于）, 'in'（包含）, 'nin'（不包含）, 'empty'（为空）, 'nempty'（不为空）
    // 'gt'（大于）, 'gte'（大于等于）, 'lt'（小于）, 'lte'（小于等于）, 'between'（介于）, 'nbtn'（不介于）
    'visitorName': { type: 'string', condition: ['in'] }, // 访客名
    '_id': { type: 'string', condition: ['in', 'nin'] }, // 会话id
    'platform': { type: 'select', condition: ['eq', 'neq', 'in', 'nin'] },
    'accessId': { type: 'select', condition: ['eq', 'neq', 'in', 'nin'], props: { label: 'name', value: 'accessId' } }, // 接入号
    'toPeer': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 技能组
    // usergentName: { type: 'string', condition: ['empty', 'nempty', 'eq', 'in', 'nin'] }, // 座席昵称
    'userId': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'], props: { label: 'agentName', value: '_id' } }, // 座席名称/昵称
    'status': { type: 'select', condition: ['eq', 'neq', 'in', 'nin'] }, // 状态
    'createTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 会话创建时间
    'convertManualTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 转人工时间
    'manualTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 转人工成功时间
    'endTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] }, // 会话结束时间
    'agentFirstReplyTime': { type: 'date', condition: ['gt', 'lt', 'between'] }, // 座席回复时间
    'totalMessageCount': { type: 'number', condition: ['eq', 'gte', 'lte'] }, // 总消息数
    'visitorMessageCount': { type: 'number', condition: ['eq', 'gte', 'lte'] }, // 访客消息数
    'agentReplyMessageCount': { type: 'number', condition: ['eq', 'gte', 'lte'] }, // 座席消息数
    'seoSource': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in'] }, // 访问来源
    'seoKeywords': { type: 'string', condition: ['empty', 'nempty', 'eq', 'neq', 'in'] }, // 搜索关键字
    'finishKey': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 结束类型
    'area': { type: 'string', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 地域
    'ip': { type: 'string', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // ip
    'sessionType': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 会话类型
    'satisfactionData.satisfactionName': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'] }, // 满意度名称
    'sessionTags': { // 会话标签
      type: 'cascader',
      condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'],
      props: { label: 'name', value: '_id', children: 'children', multiple: true, emitPath: 'false' }
    },
    'messageKeywords': { // 会话内容搜索
      type: 'select',
      condition: ['in'],
      props: { multiple: true, allowCreate: true, allowCreateLength: 3 }
    },
    'applyQualityTime': { type: 'date', condition: ['gt', 'lt', 'between'] }, // 座席提交时间
    'qualityConfigName': { type: 'select', condition: ['eq', 'neq', 'in', 'nin'] }, // 质检模板
    'gradeScore': { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] }, // 质检分数
    'scoreRange': { type: 'number', condition: ['eq', 'neq', 'in', 'nin'] }, // 分数段评级
    'qualityTime': { type: 'date', condition: ['eq', 'gt', 'lt', 'between'] },
    'qualityUser': { type: 'select', condition: ['empty', 'nempty', 'eq', 'neq', 'in', 'nin'], props: { label: 'value', value: 'key' } }
  }

  private advanceQuery: any = []
  private query: any = {}

  private closeDraw () {
    this.drawerShow = false
  }

  private getAgentName (agentId) {
    const agent = (CommonModule as any).publicCache.userListObj[agentId]
    if (agent) {
      return agent.name
    }
    return '--'
  }

  private getAccessName (accessId: any) {
    const accessObj = (CommonModule as any).publicCache.channelList.map(v => {
      if (v.accessId === accessId) {
        return v
      }
    })

    if (accessObj && accessObj.name) {
      return accessObj.name
    }

    return '--'
  }

  private toDetail (row: any) {
    this.resultId = row.resultID
    this.qualityResults = deepClone(row)
    this.setScoreInfo({
      sessionId: row._id,
      createTime: row.applyQualityTime,
      visitorId: row.visitorId
    })
    this.drawerName = '详情'
    this.drawerShow = true
    this.logShow = false
    this.addLog(row.resultID)
    this.$nextTick(() => {
      this.resultDetail.init()
    })
  }

  private addLog (id: any) { // 添加日志
    const params = {
      url: '/im-center/action/quality/enterQualitySession',
      method: 'POST',
      data: {
        qualitySessionId: id
      }
    }
    commonAction(params)
  }

  private setScoreInfo ({ sessionId, createTime, visitorId }) {
    this.currentSessionId = sessionId;
    this.currentSessionCreateTime = createTime;
    this.currentVisitorId = visitorId;
  }

  private toLog (row: any) {
    this.drawerName = '日志'
    this.drawerShow = true
    this.logShow = true
    this.resultId = row.resultID
    this.$nextTick(() => {
      this.qualityLog.getLogData()
    })
  }

  private handleSearchFunc () {
    this.pagingData.page = 1
    this.getData()
  }

  private checkHeadersChange (checkList: any, isInit: any) {
    this.$set(this, 'checkHeaders', checkList)
    if (!isInit) {
      this.saveWebchatTabelHeaders(checkList)
    }
  }

  private saveWebchatTabelHeaders (headers: any) { // 自定义表头保存
    if (headers[headers.length - 1].prop === 'oprate') { // 如果表头最后一项是操作需去掉，操作不入库
      headers = headers.slice(0, headers.length - 1)
    }
    const sendData: any = {
      menu: 'qc_webchat_session_query_header',
      fields: headers
    }
    if (this.customHeaderUpdateId) {
      sendData._id = this.customHeaderUpdateId
    }
    const data = { url: '/im-center/action/searchHeaderConfig/save', method: 'POST', data: sendData }
    commonAction(data)
  }

  private getWebchatTabelHeaders () { // 获取自定义表头
    this.showLoading = true
    this.isShowTabel = false
    const params = { url: '/im-center/action/searchHeaderConfig/query', method: 'POST', data: { menu: 'qc_webchat_session_query_header' } }
    commonAction(params).then((res: any) => {
      if (res.success && res.data && res.data.fields && res.data.fields.length) {
        this.customHeaderUpdateId = res.data._id
        res.data.fields.push({ label: '操作', prop: 'oprate', disenable: true })
        this.$set(this, 'tableHeaders', res.data.fields)
      }
      this.$nextTick(() => {
        this.isShowTabel = true
      })
      this.showLoading = false
    })
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.getData()
  }

  private async getData (source = '') {
    this.showLoading = true
    // 搜索区间最大值最小值必填-两端值一个存在或都不存在为[]
    const cloneForm = deepClone(this.formData)
    const ranges = ['agentFirstReplyLength', 'totalMessageCount', 'agentReplyMessageCount', 'sesssionTimeLength', 'gradeScore']
    ranges.forEach(item => {
      if (cloneForm[item][0] && cloneForm[item][1]) {
        if (['agentFirstReplyLength', 'sesssionTimeLength'].includes(item)) { // 转换为时间戳
          cloneForm[item][0] = cloneForm[item][0] * 1000
          cloneForm[item][1] = cloneForm[item][1] * 1000
        }
      } else {
        cloneForm[item] = []
      }
    })

    if (source === 'custom') {
      this.query = {}
      if (this.advanceQuery && this.advanceQuery.length > 0) {
        this.query.advanceQuery = this.advanceQuery
      } else {
        delete this.query.advanceQuery
      }
    };
    const sendData = {
      page: this.pagingData.page,
      limit: this.pagingData.limit,
      query: cloneForm,
      ...this.query
    }
    const res: any = await commonAction({ url: '/im-center/action/quality/queryQualityResult', method: 'POST', data: sendData })
    if (res.success && res.data) {
      const channelList = this.$store.state.common.publicCache.channelList || []
      const resultItemList: any = [];
      res.data.list.forEach((result: any) => {
        const item = result.data || {};
        item.resultID = result._id;
        const accessObj = channelList.find((channelItem: any) => { // 接入号
          return channelItem.accessId === item.accessId
        })
        item.accessName = accessObj ? accessObj.name : '--'
        item.agentName = this.getAgentName(item.userId)
        item.qualityUserName = this.getAgentName(item.qualityUser)
        const queueObj = this.$store.state.common.publicCache.queueListObj[item.toPeer] // 技能组
        item.queueName = queueObj ? queueObj.name : '--'
        item.satisfactionName = item.satisfactionData && item.satisfactionData.satisfactionName ? item.satisfactionData.satisfactionName : '' // 满意度名称
        const sessionTagsInfoObj = {}
        if (item.sessionTagsInfo) {
          item.sessionTagsInfo.forEach(tagInfoItem => {
            sessionTagsInfoObj[tagInfoItem._id] = tagInfoItem
          })
        }
        if (item.sessionTags && item.sessionTags.length > 0) {
          const arr: any = []
          item.sessionTags.forEach((sessionTagItem: any) => {
            if (this.webchatLabelTreeObj[sessionTagItem]) {
              arr.push(this.webchatLabelTreeObj[sessionTagItem])
            } else {
              arr.push(sessionTagsInfoObj[sessionTagItem])
            }
          })
          item.sessionTags = arr
        } else {
          item.sessionTags = []
        }
        if (item.manualTimestamp && item.agentFirstReplyTimestamp) {
          item.agentFirstReplyLength = millsToDate(item.agentFirstReplyTimestamp - (item.manualTimestamp || item.createTimestamp)) // 首次响应时长
        } else {
          item.agentFirstReplyLength = '--'
        }
        item.sesssionTimeLength = item.sesssionTimeLength ? millsToDate(item.sesssionTimeLength) : '--' // 对话时长
        resultItemList.push(item);
      })
      this.qualityTableData = resultItemList || []
      this.pagingData.total = res.data.count || 0
      this.showLoading = false
    }
  }

  private handleLines () {
    this.openShow = !this.openShow
  }

  private updatePropValue (val: any, field: any) {
    this.$set(this.formData, field, val)
  }

  private saveFilter (data: any) {
    const sendData = {
      fields: data.fields,
      menu: 'qc_webchat_session_query'
    }
    const params = {
      url: '/im-center/action/searchHeaderConfig/save',
      method: 'POST',
      data: this.customFilterUpdateId ? { ...sendData, _id: this.customFilterUpdateId } : sendData
    }
    commonAction(params).then(res => {
      if (res.success) {
        this.$message.success('保存成功')
        this.updateFilter(data.fields)
      }
    })
  }

  private updateFilter (chooseData: any) {
    chooseData.forEach(item => {
      this.getNewChoices(item)
    })
    this.$set(this, 'chooseFilterField', chooseData)
    this.$nextTick(() => {
      this.searchHeight = document.getElementById('searchForm')?.offsetHeight
    })
  }

  private getNewChoices (item: any) {
    switch (item.field) {
      case 'toPeer':
        this.$set(item, 'choices', this.queueList)
        break
      case 'userId':
        this.$set(item, 'choices', this.getUserList)
        break
      case 'finishReason':
        this.$set(item, 'choices', this.finishKeyOpt)
        break
      case 'accessId':
        this.$set(item, 'choices', this.accessIdOpt)
        break
      case 'qualityUser':
        this.$set(item, 'choices', this.getUserList)
        break
      case 'name':
        this.$set(item, 'choices', this.modelsList)
        break
    }
  }

  private getFilterConf () { // 获取自定义搜索
    const params = {
      url: '/im-center/action/searchHeaderConfig/query',
      method: 'POST',
      data: {
        menu: 'qc_webchat_session_query'
      }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        this.customFilterUpdateId = res.data._id
        // 涉及到缓存数据 需要更新
        this.updateFilter(res.data.fields)
      }
    })
  }

  private handleSearch (advanceQuery) {
    this.pagingData.page = 1
    this.advanceQuery = advanceQuery;
    (this.$refs as any).customSearch.hide()
    this.getData('custom')
  }

  private getConfig () { // 获取模板
    const params = {
      url: '/im-center/action/qualityConfig/query',
      method: 'POST',
      data: {
        page: 1,
        limit: 1000
      }
    }
    commonAction(params).then(res => {
      if (res.success && res.data) {
        const models = res.data.map(item => {
          return {
            value: item.name,
            key: item._id,
            ...item
          }
        })
        this.searchFields.forEach(item => {
          if (item.field === 'name') {
            this.$set(item, 'choices', models)
          }
        })
        this.modelsList = models
      }
    })
  }

  private async activated () {
    this.getConfig()
    this.getFilterConf()
  }

  private beforeMount () {
    this.$getCache('/im-center/action/webchat/cache', ['finishKey'], true, true, true, 'POST', true).then((res: any) => {
      if (res && res.success) {
        this.finishKeyOpt = res.finishKey.map(item => {
          return {
            value: item.name,
            key: item._id
          }
        })
      }
    })
  }

  private mounted () {
    this.getWebchatTabelHeaders()
    const channelCache = this.$getCache('/im-center/action/webchat/channelCache', ['channelList'], true) // 获取渠道列表
    Promise.all([channelCache]).then(res => {
      this.getData()
    })
  }
}
</script>
<style lang="stylus" scoped>
.customSearch
  margin-right 10px
>>> .drawer-contain
  padding 0 !important
  overflow hidden !important
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
>>> .el-form-item__label
  line-height 1
>>> .el-form-item__content
  display flex
  align-items center
>>> .oprate
  margin-top 20px
.open
  width 70px
  height 32px
  display flex
  align-items center
  justify-content center
  font-size 12px
  color #303854
  border 1px solid #E7E9ED
  border-radius 4px
  margin-right 10px
  cursor pointer
  i
    margin-right 5px
</style>
